<!DOCTYPE html>
<html>
  <head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport">
  <meta name="description" content="刘清政">
  <meta name="keyword" content="hexo-theme">
  
    <link rel="shortcut icon" href="/css/images/logo.png">
  
  <title>
    
      python/Django-rest-framework框架/9-drf-JWT认证 | Justin-刘清政的博客
    
  </title>
  <link href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
  <link href="//cdnjs.cloudflare.com/ajax/libs/nprogress/0.2.0/nprogress.min.css" rel="stylesheet">
  <link href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/tomorrow.min.css" rel="stylesheet">
  
<link rel="stylesheet" href="/css/style.css">

  
    
<link rel="stylesheet" href="/css/plugins/gitment.css">

  
  <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/geopattern/1.2.3/js/geopattern.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/nprogress/0.2.0/nprogress.min.js"></script>
  
    
<script src="/js/qrious.js"></script>

  
  
    
<script src="/js/gitment.js"></script>

  
  

  
<meta name="generator" content="Hexo 4.2.0"></head>
<div class="wechat-share">
  <img src="/css/images/logo.png" />
</div>

  <body>
    <header class="header fixed-header">
  <div class="header-container">
    <a class="home-link" href="/">
      <div class="logo"></div>
      <span>Justin-刘清政的博客</span>
    </a>
    <ul class="right-list">
      
        <li class="list-item">
          
            <a href="/" class="item-link">主页</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/tags/" class="item-link">标签</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/archives/" class="item-link">归档</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/about/" class="item-link">关于我</a>
          
        </li>
      
    </ul>
    <div class="menu">
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </div>
    <div class="menu-mask">
      <ul class="menu-list">
        
          <li class="menu-item">
            
              <a href="/" class="menu-link">主页</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/tags/" class="menu-link">标签</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/archives/" class="menu-link">归档</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/about/" class="menu-link">关于我</a>
            
          </li>
        
      </ul>
    </div>
  </div>
</header>

    <div id="article-banner">
  <h2>python/Django-rest-framework框架/9-drf-JWT认证</h2>



  <p class="post-date">2020-06-28</p>
    <!-- 不蒜子统计 -->
    <span id="busuanzi_container_page_pv" style='display:none' class="">
        <i class="icon-smile icon"></i> 阅读数：<span id="busuanzi_value_page_pv"></span>次
    </span>
  <div class="arrow-down">
    <a href="javascript:;"></a>
  </div>
</div>
<main class="app-body flex-box">
  <!-- Article START -->
  <article class="post-article">
    <section class="markdown-content"><h1 id="一-JWT认证"><a href="#一-JWT认证" class="headerlink" title="一 JWT认证"></a>一 JWT认证</h1><p>在用户注册或登录后，我们想记录用户的登录状态，或者为用户创建身份认证的凭证。我们不再使用Session认证机制，而使用Json Web Token（本质就是token）认证机制。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Json web token (JWT), 是为了在网络应用环境间传递声明而执行的一种基于JSON的开放标准（(RFC 7519).该token被设计为紧凑且安全的，特别适用于分布式站点的单点登录（SSO）场景。JWT的声明一般被用来在身份提供者和服务提供者间传递被认证的用户身份信息，以便于从资源服务器获取资源，也可以增加一些额外的其它业务逻辑所必须的声明信息，该token也可直接被用于认证，也可被加密。</span><br></pre></td></tr></table></figure>

<p><img src="https://tva1.sinaimg.cn/large/007S8ZIlgy1ggprivsr69j31i50u0tao.jpg" alt=""></p>
<p><img src="https://tva1.sinaimg.cn/large/007S8ZIlgy1ggpriyyay5j31i80u03zl.jpg" alt=""></p>
<p><img src="https://tva1.sinaimg.cn/large/007S8ZIlgy1ggprj27cflj31fq0u0abx.jpg" alt=""></p>
<p><img src="https://tva1.sinaimg.cn/large/007S8ZIlgy1ggprj5moolj31ob0u0q4w.jpg" alt=""></p>
<h2 id="1-1-构成和工作原理"><a href="#1-1-构成和工作原理" class="headerlink" title="1.1 构成和工作原理"></a>1.1 构成和工作原理</h2><h3 id="JWT的构成"><a href="#JWT的构成" class="headerlink" title="JWT的构成"></a>JWT的构成</h3><p>JWT就是一段字符串，由三段信息构成的，将这三段信息文本用<code>.</code>链接一起就构成了Jwt字符串。就像这样:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ</span><br></pre></td></tr></table></figure>

<p>第一部分我们称它为头部（header),第二部分我们称其为载荷（payload, 类似于飞机上承载的物品)，第三部分是签证（signature).</p>
<h3 id="1-1-1-header"><a href="#1-1-1-header" class="headerlink" title="1.1.1 header"></a>1.1.1 header</h3><p>jwt的头部承载两部分信息：</p>
<ul>
<li>声明类型，这里是jwt</li>
<li>声明加密的算法 通常直接使用 HMAC SHA256</li>
</ul>
<p>完整的头部就像下面这样的JSON：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  &#39;typ&#39;: &#39;JWT&#39;,</span><br><span class="line">  &#39;alg&#39;: &#39;HS256&#39;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>然后将头部进行base64加密（该加密是可以对称解密的),构成了第一部分.</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9</span><br></pre></td></tr></table></figure>

<h3 id="1-1-2-payload"><a href="#1-1-2-payload" class="headerlink" title="1.1.2 payload"></a>1.1.2 payload</h3><p>载荷就是存放有效信息的地方。这个名字像是特指飞机上承载的货品，这些有效信息包含三个部分</p>
<ul>
<li>标准中注册的声明</li>
<li>公共的声明</li>
<li>私有的声明</li>
</ul>
<p><strong>标准中注册的声明</strong> (建议但不强制使用) ：</p>
<ul>
<li><strong>iss</strong>: jwt签发者</li>
<li><strong>sub</strong>: jwt所面向的用户</li>
<li><strong>aud</strong>: 接收jwt的一方</li>
<li><strong>exp</strong>: jwt的过期时间，这个过期时间必须要大于签发时间</li>
<li><strong>nbf</strong>: 定义在什么时间之前，该jwt都是不可用的.</li>
<li><strong>iat</strong>: jwt的签发时间</li>
<li><strong>jti</strong>: jwt的唯一身份标识，主要用来作为一次性token,从而回避时序攻击。</li>
</ul>
<p><strong>公共的声明</strong> ： 公共的声明可以添加任何的信息，一般添加用户的相关信息或其他业务需要的必要信息.但不建议添加敏感信息，因为该部分在客户端可解密.</p>
<p><strong>私有的声明</strong> ： 私有声明是提供者和消费者所共同定义的声明，一般不建议存放敏感信息，因为base64是对称解密的，意味着该部分信息可以归类为明文信息。</p>
<p>定义一个payload:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  &quot;sub&quot;: &quot;1234567890&quot;,</span><br><span class="line">  &quot;name&quot;: &quot;John Doe&quot;,</span><br><span class="line">  &quot;admin&quot;: true</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>然后将其进行base64加密，得到JWT的第二部分。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9</span><br></pre></td></tr></table></figure>

<h3 id="1-1-3-signature"><a href="#1-1-3-signature" class="headerlink" title="1.1.3 signature"></a>1.1.3 signature</h3><p>JWT的第三部分是一个签证信息，这个签证信息由三部分组成：</p>
<ul>
<li>header (base64后的)</li>
<li>payload (base64后的)</li>
<li>secret</li>
</ul>
<p>这个部分需要base64加密后的header和base64加密后的payload使用<code>.</code>连接组成的字符串，然后通过header中声明的加密方式进行加盐<code>secret</code>组合加密，然后就构成了jwt的第三部分。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F; javascript</span><br><span class="line">var encodedString &#x3D; base64UrlEncode(header) + &#39;.&#39; + base64UrlEncode(payload);</span><br><span class="line"></span><br><span class="line">var signature &#x3D; HMACSHA256(encodedString, &#39;secret&#39;); &#x2F;&#x2F; TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ</span><br></pre></td></tr></table></figure>

<p>将这三部分用<code>.</code>连接成一个完整的字符串,构成了最终的jwt:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ</span><br></pre></td></tr></table></figure>

<p><strong>注意：secret是保存在服务器端的，jwt的签发生成也是在服务器端的，secret就是用来进行jwt的签发和jwt的验证，所以，它就是你服务端的私钥，在任何场景都不应该流露出去。一旦客户端得知这个secret, 那就意味着客户端是可以自我签发jwt了。</strong></p>
<p><strong>关于签发和核验JWT，我们可以使用Django REST framework JWT扩展来完成。</strong></p>
<p>文档网站：<a href="http://getblimp.github.io/django-rest-framework-jwt/" target="_blank" rel="noopener">http://getblimp.github.io/django-rest-framework-jwt/</a></p>
<h2 id="1-2-本质原理"><a href="#1-2-本质原理" class="headerlink" title="1.2 本质原理"></a>1.2 本质原理</h2><h2 id="jwt认证算法：签发与校验"><a href="#jwt认证算法：签发与校验" class="headerlink" title="jwt认证算法：签发与校验"></a>jwt认证算法：签发与校验</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">"""</span></span><br><span class="line"><span class="string">1）jwt分三段式：头.体.签名 （head.payload.sgin）</span></span><br><span class="line"><span class="string">2）头和体是可逆加密，让服务器可以反解出user对象；签名是不可逆加密，保证整个token的安全性的</span></span><br><span class="line"><span class="string">3）头体签名三部分，都是采用json格式的字符串，进行加密，可逆加密一般采用base64算法，不可逆加密一般采用hash(md5)算法</span></span><br><span class="line"><span class="string">4）头中的内容是基本信息：公司信息、项目组信息、token采用的加密方式信息</span></span><br><span class="line"><span class="string">&#123;</span></span><br><span class="line"><span class="string">	"company": "公司信息",</span></span><br><span class="line"><span class="string">	...</span></span><br><span class="line"><span class="string">&#125;</span></span><br><span class="line"><span class="string">5）体中的内容是关键信息：用户主键、用户名、签发时客户端信息(设备号、地址)、过期时间</span></span><br><span class="line"><span class="string">&#123;</span></span><br><span class="line"><span class="string">	"user_id": 1,</span></span><br><span class="line"><span class="string">	...</span></span><br><span class="line"><span class="string">&#125;</span></span><br><span class="line"><span class="string">6）签名中的内容时安全信息：头的加密结果 + 体的加密结果 + 服务器不对外公开的安全码 进行md5加密</span></span><br><span class="line"><span class="string">&#123;</span></span><br><span class="line"><span class="string">	"head": "头的加密字符串",</span></span><br><span class="line"><span class="string">	"payload": "体的加密字符串",</span></span><br><span class="line"><span class="string">	"secret_key": "安全码"</span></span><br><span class="line"><span class="string">&#125;</span></span><br><span class="line"><span class="string">"""</span></span><br></pre></td></tr></table></figure>

<h5 id="签发：根据登录请求提交来的-账号-密码-设备信息-签发-token"><a href="#签发：根据登录请求提交来的-账号-密码-设备信息-签发-token" class="headerlink" title="签发：根据登录请求提交来的 账号 + 密码 + 设备信息 签发 token"></a>签发：根据登录请求提交来的 账号 + 密码 + 设备信息 签发 token</h5><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">"""</span></span><br><span class="line"><span class="string">1）用基本信息存储json字典，采用base64算法加密得到 头字符串</span></span><br><span class="line"><span class="string">2）用关键信息存储json字典，采用base64算法加密得到 体字符串</span></span><br><span class="line"><span class="string">3）用头、体加密字符串再加安全码信息存储json字典，采用hash md5算法加密得到 签名字符串</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">账号密码就能根据User表得到user对象，形成的三段字符串用 . 拼接成token返回给前台</span></span><br><span class="line"><span class="string">"""</span></span><br></pre></td></tr></table></figure>

<h5 id="校验：根据客户端带token的请求-反解出-user-对象"><a href="#校验：根据客户端带token的请求-反解出-user-对象" class="headerlink" title="校验：根据客户端带token的请求 反解出 user 对象"></a>校验：根据客户端带token的请求 反解出 user 对象</h5><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">"""</span></span><br><span class="line"><span class="string">1）将token按 . 拆分为三段字符串，第一段 头加密字符串 一般不需要做任何处理</span></span><br><span class="line"><span class="string">2）第二段 体加密字符串，要反解出用户主键，通过主键从User表中就能得到登录用户，过期时间和设备信息都是安全信息，确保token没过期，且时同一设备来的</span></span><br><span class="line"><span class="string">3）再用 第一段 + 第二段 + 服务器安全码 不可逆md5加密，与第三段 签名字符串 进行碰撞校验，通过后才能代表第二段校验得到的user对象就是合法的登录用户</span></span><br><span class="line"><span class="string">"""</span></span><br></pre></td></tr></table></figure>



<h2 id="drf项目的jwt认证开发流程（重点）"><a href="#drf项目的jwt认证开发流程（重点）" class="headerlink" title="drf项目的jwt认证开发流程（重点）"></a>drf项目的jwt认证开发流程（重点）</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">"""</span></span><br><span class="line"><span class="string">1）用账号密码访问登录接口，登录接口逻辑中调用 签发token 算法，得到token，返回给客户端，客户端自己存到cookies中</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">2）校验token的算法应该写在认证类中(在认证类中调用)，全局配置给认证组件，所有视图类请求，都会进行认证校验，所以请求带了token，就会反解出user对象，在视图类中用request.user就能访问登录的用户</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">注：登录接口需要做 认证 + 权限 两个局部禁用</span></span><br><span class="line"><span class="string">"""</span></span><br></pre></td></tr></table></figure>



<h3 id="1-2-1-补充base64编码解码"><a href="#1-2-1-补充base64编码解码" class="headerlink" title="1.2.1 补充base64编码解码"></a>1.2.1 补充base64编码解码</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> base64</span><br><span class="line"><span class="keyword">import</span> json</span><br><span class="line">dic_info=&#123;</span><br><span class="line">  <span class="string">"sub"</span>: <span class="string">"1234567890"</span>,</span><br><span class="line">  <span class="string">"name"</span>: <span class="string">"lqz"</span>,</span><br><span class="line">  <span class="string">"admin"</span>: <span class="literal">True</span></span><br><span class="line">&#125;</span><br><span class="line">byte_info=json.dumps(dic_info).encode(<span class="string">'utf-8'</span>)</span><br><span class="line"><span class="comment"># base64编码</span></span><br><span class="line">base64_str=base64.b64encode(byte_info)</span><br><span class="line">print(base64_str)</span><br><span class="line"><span class="comment"># base64解码</span></span><br><span class="line">base64_str=<span class="string">'eyJzdWIiOiAiMTIzNDU2Nzg5MCIsICJuYW1lIjogImxxeiIsICJhZG1pbiI6IHRydWV9'</span></span><br><span class="line">str_url = base64.b64decode(base64_str).decode(<span class="string">"utf-8"</span>)</span><br><span class="line">print(str_url)</span><br></pre></td></tr></table></figure>



<h2 id="二-drf-jwt安装和简单使用"><a href="#二-drf-jwt安装和简单使用" class="headerlink" title="二 drf-jwt安装和简单使用"></a>二 drf-jwt安装和简单使用</h2><h5 id="2-1-官网"><a href="#2-1-官网" class="headerlink" title="2.1 官网"></a>2.1 官网</h5><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">http://getblimp.github.io/django-rest-framework-jwt/</span><br></pre></td></tr></table></figure>

<h5 id="2-2-安装"><a href="#2-2-安装" class="headerlink" title="2.2 安装"></a>2.2 安装</h5><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">pip install djangorestframework-jwt</span><br></pre></td></tr></table></figure>

<h5 id="2-3-使用："><a href="#2-3-使用：" class="headerlink" title="2.3 使用："></a>2.3 使用：</h5><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 1 创建超级用户</span></span><br><span class="line">python3 manage.py createsuperuser</span><br><span class="line"><span class="comment"># 2 配置路由urls.py</span></span><br><span class="line"><span class="keyword">from</span> django.urls <span class="keyword">import</span> path</span><br><span class="line"><span class="keyword">from</span> rest_framework_jwt.views <span class="keyword">import</span> obtain_jwt_token</span><br><span class="line">urlpatterns = [</span><br><span class="line">    path(<span class="string">'login/'</span>, obtain_jwt_token),</span><br><span class="line">]</span><br><span class="line"><span class="comment"># 3 postman测试</span></span><br><span class="line">向后端接口发送post请求，携带用户名密码，即可看到生成的token</span><br><span class="line"></span><br><span class="line"><span class="comment"># 4 setting.py中配置认证使用jwt提供的jsonwebtoken</span></span><br><span class="line"><span class="comment"># 5 postman发送访问请求（必须带jwt空格）</span></span><br></pre></td></tr></table></figure>

<h2 id="三-实战之使用Django-auth的User表自动签发"><a href="#三-实战之使用Django-auth的User表自动签发" class="headerlink" title="三 实战之使用Django auth的User表自动签发"></a>三 实战之使用Django auth的User表自动签发</h2><h3 id="3-1-配置setting-py"><a href="#3-1-配置setting-py" class="headerlink" title="3.1 配置setting.py"></a>3.1 配置setting.py</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> datetime</span><br><span class="line">JWT_AUTH = &#123;</span><br><span class="line">    <span class="comment"># 过期时间1天</span></span><br><span class="line">    <span class="string">'JWT_EXPIRATION_DELTA'</span>: datetime.timedelta(days=<span class="number">1</span>),</span><br><span class="line">    <span class="comment"># 自定义认证结果：见下方序列化user和自定义response</span></span><br><span class="line">  	<span class="comment"># 如果不自定义，返回的格式是固定的，只有token字段</span></span><br><span class="line">    <span class="string">'JWT_RESPONSE_PAYLOAD_HANDLER'</span>: <span class="string">'users.utils.jwt_response_payload_handler'</span>,  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="3-2-编写序列化类ser-py"><a href="#3-2-编写序列化类ser-py" class="headerlink" title="3.2 编写序列化类ser.py"></a>3.2 编写序列化类ser.py</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> rest_framework <span class="keyword">import</span> serializers</span><br><span class="line"><span class="keyword">from</span> users <span class="keyword">import</span> models</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">UserModelSerializers</span><span class="params">(serializers.ModelSerializer)</span>:</span></span><br><span class="line">    <span class="class"><span class="keyword">class</span> <span class="title">Meta</span>:</span></span><br><span class="line">        model = models.UserInfo</span><br><span class="line">        fields = [<span class="string">'username'</span>]</span><br></pre></td></tr></table></figure>

<h5 id="3-3-自定义认证返回结果（setting中配置的）"><a href="#3-3-自定义认证返回结果（setting中配置的）" class="headerlink" title="3.3 自定义认证返回结果（setting中配置的）"></a>3.3 自定义认证返回结果（setting中配置的）</h5><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#utils.py</span></span><br><span class="line"><span class="keyword">from</span> users.ser <span class="keyword">import</span> UserModelSerializers</span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">jwt_response_payload_handler</span><span class="params">(token, user=None, request=None)</span>:</span></span><br><span class="line">    <span class="keyword">return</span> &#123;</span><br><span class="line">        <span class="string">'status'</span>: <span class="number">0</span>,</span><br><span class="line">        <span class="string">'msg'</span>: <span class="string">'ok'</span>,</span><br><span class="line">        <span class="string">'data'</span>: &#123;</span><br><span class="line">            <span class="string">'token'</span>: token,</span><br><span class="line">            <span class="string">'user'</span>: UserModelSerializers(user).data</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<h3 id="3-4-基于drf-jwt的全局认证："><a href="#3-4-基于drf-jwt的全局认证：" class="headerlink" title="3.4 基于drf-jwt的全局认证："></a>3.4 基于drf-jwt的全局认证：</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#app_auth.py(自己创建)</span></span><br><span class="line"><span class="keyword">from</span> rest_framework.exceptions <span class="keyword">import</span> AuthenticationFailed</span><br><span class="line"><span class="keyword">from</span> rest_framework_jwt.authentication <span class="keyword">import</span> jwt_decode_handler</span><br><span class="line"><span class="keyword">from</span> rest_framework_jwt.authentication <span class="keyword">import</span> get_authorization_header,jwt_get_username_from_payload</span><br><span class="line"><span class="keyword">from</span> rest_framework_jwt.authentication <span class="keyword">import</span> BaseJSONWebTokenAuthentication</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">JSONWebTokenAuthentication</span><span class="params">(BaseJSONWebTokenAuthentication)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">authenticate</span><span class="params">(self, request)</span>:</span></span><br><span class="line">        jwt_value = get_authorization_header(request)</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> jwt_value:</span><br><span class="line">            <span class="keyword">raise</span> AuthenticationFailed(<span class="string">'Authorization 字段是必须的'</span>)</span><br><span class="line">        <span class="keyword">try</span>:</span><br><span class="line">            payload = jwt_decode_handler(jwt_value)</span><br><span class="line">        <span class="keyword">except</span> jwt.ExpiredSignature:</span><br><span class="line">            <span class="keyword">raise</span> AuthenticationFailed(<span class="string">'签名过期'</span>)</span><br><span class="line">        <span class="keyword">except</span> jwt.InvalidTokenError:</span><br><span class="line">            <span class="keyword">raise</span> AuthenticationFailed(<span class="string">'非法用户'</span>)</span><br><span class="line">        user = self.authenticate_credentials(payload)</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> user, jwt_value</span><br></pre></td></tr></table></figure>

<h3 id="3-5-全局使用"><a href="#3-5-全局使用" class="headerlink" title="3.5 全局使用"></a>3.5 全局使用</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># setting.py</span></span><br><span class="line">REST_FRAMEWORK = &#123;</span><br><span class="line">    <span class="comment"># 认证模块</span></span><br><span class="line">    <span class="string">'DEFAULT_AUTHENTICATION_CLASSES'</span>: (</span><br><span class="line">        <span class="string">'users.app_auth.JSONWebTokenAuthentication'</span>,</span><br><span class="line">    ),</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="3-6-局部启用禁用"><a href="#3-6-局部启用禁用" class="headerlink" title="3.6 局部启用禁用"></a>3.6 局部启用禁用</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 局部禁用</span></span><br><span class="line">authentication_classes = []</span><br><span class="line"><span class="comment"># 局部启用</span></span><br><span class="line"><span class="keyword">from</span> user.authentications <span class="keyword">import</span> JSONWebTokenAuthentication</span><br><span class="line">authentication_classes = [JSONWebTokenAuthentication]</span><br><span class="line"><span class="comment"># 实际代码如下view.py</span></span><br><span class="line"><span class="comment"># 自定义Response</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">CommonResponse</span><span class="params">(Response)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self,status,msg,data=<span class="string">''</span>,*args,**kwargs)</span>:</span></span><br><span class="line">        dic=&#123;<span class="string">'status'</span>:status,<span class="string">'msg'</span>:msg,<span class="string">'data'</span>:data&#125;</span><br><span class="line">        super().__init__(data=dic,*args,**kwargs)</span><br><span class="line"><span class="comment"># 测试订单接口</span></span><br><span class="line"><span class="keyword">from</span> users.app_auth <span class="keyword">import</span> JSONWebTokenAuthentication</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">OrderView</span><span class="params">(APIView)</span>:</span></span><br><span class="line">    <span class="comment"># authentication_classes = [JSONWebTokenAuthentication]</span></span><br><span class="line">    authentication_classes = []</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">get</span><span class="params">(self,request)</span>:</span></span><br><span class="line">        <span class="keyword">return</span> CommonResponse(<span class="string">'100'</span>, <span class="string">'成功'</span>,&#123;<span class="string">'数据'</span>:<span class="string">'测试'</span>&#125;)</span><br></pre></td></tr></table></figure>

<h3 id="3-7-多方式登录："><a href="#3-7-多方式登录：" class="headerlink" title="3.7 多方式登录："></a>3.7 多方式登录：</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">## views.py</span></span><br><span class="line"><span class="comment"># 重点：自定义login，完成多方式登录</span></span><br><span class="line"><span class="keyword">from</span> rest_framework.viewsets <span class="keyword">import</span> ViewSet</span><br><span class="line"><span class="keyword">from</span> rest_framework.response <span class="keyword">import</span> Response</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">LoginViewSet</span><span class="params">(ViewSet)</span>:</span></span><br><span class="line">    <span class="comment"># 需要和mixins结合使用，继承GenericViewSet，不需要则继承ViewSet</span></span><br><span class="line">    <span class="comment"># 为什么继承视图集，不去继承工具视图或视图基类，因为视图集可以自定义路由映射：</span></span><br><span class="line">    <span class="comment">#       可以做到get映射get，get映射list，还可以做到自定义（灵活）</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">login</span><span class="params">(self, request, *args, **kwargs)</span>:</span></span><br><span class="line">        serializer = serializers.LoginSerializer(data=request.data, context=&#123;<span class="string">'request'</span>: request&#125;)</span><br><span class="line">        serializer.is_valid(raise_exception=<span class="literal">True</span>)</span><br><span class="line">        token = serializer.context.get(<span class="string">'token'</span>)</span><br><span class="line">        <span class="keyword">return</span> Response(&#123;<span class="string">"token"</span>: token&#125;)</span><br><span class="line">      </span><br><span class="line">      </span><br><span class="line">      </span><br><span class="line"></span><br><span class="line"><span class="comment">## ser.py</span></span><br><span class="line"><span class="comment"># 重点：自定义login，完成多方式登录</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">LoginSerializer</span><span class="params">(serializers.ModelSerializer)</span>:</span></span><br><span class="line">    <span class="comment"># 登录请求，走的是post方法，默认post方法完成的是create入库校验，所以唯一约束的字段，会进行数据库唯一校验，导致逻辑相悖</span></span><br><span class="line">    <span class="comment"># 需要覆盖系统字段，自定义校验规则，就可以避免完成多余的不必要校验，如唯一字段校验</span></span><br><span class="line">    username = serializers.CharField()</span><br><span class="line">    <span class="class"><span class="keyword">class</span> <span class="title">Meta</span>:</span></span><br><span class="line">        model = models.User</span><br><span class="line">        <span class="comment"># 结合前台登录布局：采用账号密码登录，或手机密码登录，布局一致，所以不管账号还是手机号，都用username字段提交的</span></span><br><span class="line">        fields = (<span class="string">'username'</span>, <span class="string">'password'</span>)</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">validate</span><span class="params">(self, attrs)</span>:</span></span><br><span class="line">        <span class="comment"># 在全局钩子中，才能提供提供的所需数据，整体校验得到user</span></span><br><span class="line">        <span class="comment"># 再就可以调用签发token算法，将user信息转换为token</span></span><br><span class="line">        <span class="comment"># 将token存放到context属性中，传给外键视图类使用</span></span><br><span class="line">        user = self._get_user(attrs)</span><br><span class="line">        payload = jwt_payload_handler(user)</span><br><span class="line">        token = jwt_encode_handler(payload)</span><br><span class="line">        self.context[<span class="string">'token'</span>] = token</span><br><span class="line">        <span class="keyword">return</span> attrs</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 多方式登录</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">_get_user</span><span class="params">(self, attrs)</span>:</span></span><br><span class="line">        username = attrs.get(<span class="string">'username'</span>)</span><br><span class="line">        password = attrs.get(<span class="string">'password'</span>)</span><br><span class="line">        <span class="keyword">import</span> re</span><br><span class="line">        <span class="keyword">if</span> re.match(<span class="string">r'^1[3-9][0-9]&#123;9&#125;$'</span>, username):</span><br><span class="line">            <span class="comment"># 手机登录</span></span><br><span class="line">            user = models.User.objects.filter(mobile=username, is_active=<span class="literal">True</span>).first()</span><br><span class="line">        <span class="keyword">elif</span> re.match(<span class="string">r'^.+@.+$'</span>, username):</span><br><span class="line">            <span class="comment"># 邮箱登录</span></span><br><span class="line">            user = models.User.objects.filter(email=username, is_active=<span class="literal">True</span>).first()</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="comment"># 账号登录</span></span><br><span class="line">            user = models.User.objects.filter(username=username, is_active=<span class="literal">True</span>).first()</span><br><span class="line">        <span class="keyword">if</span> user <span class="keyword">and</span> user.check_password(password):</span><br><span class="line">            <span class="keyword">return</span> user</span><br><span class="line"></span><br><span class="line">        <span class="keyword">raise</span> ValidationError(&#123;<span class="string">'user'</span>: <span class="string">'user error'</span>&#125;)</span><br></pre></td></tr></table></figure>



<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># utils.py</span></span><br><span class="line"><span class="keyword">import</span> re</span><br><span class="line"><span class="keyword">from</span> .models <span class="keyword">import</span> User</span><br><span class="line"><span class="keyword">from</span> django.contrib.auth.backends <span class="keyword">import</span> ModelBackend</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">JWTModelBackend</span><span class="params">(ModelBackend)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">authenticate</span><span class="params">(self, request, username=None, password=None, **kwargs)</span>:</span></span><br><span class="line">        <span class="keyword">try</span>:</span><br><span class="line">            <span class="keyword">if</span> re.match(<span class="string">r'^1[3-9]\d&#123;9&#125;$'</span>, username):</span><br><span class="line">                user = User.objects.get(mobile=username)</span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                user = User.objects.get(username=username)</span><br><span class="line">        <span class="keyword">except</span> User.DoesNotExist:</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">None</span></span><br><span class="line">        <span class="keyword">if</span> user.check_password(password) <span class="keyword">and</span> self.user_can_authenticate(user):</span><br><span class="line">            <span class="keyword">return</span> user</span><br></pre></td></tr></table></figure>

<h3 id="3-8-配置多方式登录"><a href="#3-8-配置多方式登录" class="headerlink" title="3.8 配置多方式登录"></a>3.8 配置多方式登录</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">settings.py</span><br><span class="line">AUTHENTICATION_BACKENDS = [<span class="string">'user.utils.JWTModelBackend'</span>]</span><br></pre></td></tr></table></figure>

<h2 id="四-实战之自定义User表，手动签发"><a href="#四-实战之自定义User表，手动签发" class="headerlink" title="四 实战之自定义User表，手动签发"></a>四 实战之自定义User表，手动签发</h2><h3 id="4-1-手动签发JWT："><a href="#4-1-手动签发JWT：" class="headerlink" title="4.1 手动签发JWT："></a>4.1 手动签发JWT：</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 可以拥有原生登录基于Model类user对象签发JWT</span></span><br><span class="line"><span class="keyword">from</span> rest_framework_jwt.settings <span class="keyword">import</span> api_settings</span><br><span class="line">jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER</span><br><span class="line">jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER</span><br><span class="line"></span><br><span class="line">payload = jwt_payload_handler(user)</span><br><span class="line">token = jwt_encode_handler(payload)</span><br></pre></td></tr></table></figure>

<h3 id="4-2-编写登陆视图类"><a href="#4-2-编写登陆视图类" class="headerlink" title="4.2 编写登陆视图类"></a>4.2 编写登陆视图类</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># views.py</span></span><br><span class="line"><span class="keyword">from</span> rest_framework_jwt.settings <span class="keyword">import</span> api_settings</span><br><span class="line">jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER</span><br><span class="line">jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER</span><br><span class="line"><span class="keyword">from</span> users.models <span class="keyword">import</span> User</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">LoginView</span><span class="params">(APIView)</span>:</span></span><br><span class="line">    authentication_classes = []</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">post</span><span class="params">(self,request)</span>:</span></span><br><span class="line">        username=request.data.get(<span class="string">'username'</span>)</span><br><span class="line">        password=request.data.get(<span class="string">'password'</span>)</span><br><span class="line">        user=User.objects.filter(username=username,password=password).first()</span><br><span class="line">        <span class="keyword">if</span> user: <span class="comment"># 能查到，登陆成功，手动签发</span></span><br><span class="line">            payload = jwt_payload_handler(user)</span><br><span class="line">            token = jwt_encode_handler(payload)</span><br><span class="line">            <span class="keyword">return</span> CommonResponse(<span class="string">'100'</span>,<span class="string">'登陆成功'</span>,data=&#123;<span class="string">'token'</span>:token&#125;)</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="keyword">return</span> CommonResponse(<span class="string">'101'</span>, <span class="string">'登陆失败'</span>)</span><br></pre></td></tr></table></figure>

<h3 id="4-3-编写认证组件"><a href="#4-3-编写认证组件" class="headerlink" title="4.3 编写认证组件"></a>4.3 编写认证组件</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># app_auth.py</span></span><br><span class="line"><span class="keyword">from</span> users.models <span class="keyword">import</span> User</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyJSONWebTokenAuthentication</span><span class="params">(BaseAuthentication)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">authenticate</span><span class="params">(self, request)</span>:</span></span><br><span class="line">        jwt_value = get_authorization_header(request)</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> jwt_value:</span><br><span class="line">            <span class="keyword">raise</span> AuthenticationFailed(<span class="string">'Authorization 字段是必须的'</span>)</span><br><span class="line">        <span class="keyword">try</span>:</span><br><span class="line">            payload = jwt_decode_handler(jwt_value)</span><br><span class="line">        <span class="keyword">except</span> jwt.ExpiredSignature:</span><br><span class="line">            <span class="keyword">raise</span> AuthenticationFailed(<span class="string">'签名过期'</span>)</span><br><span class="line">        <span class="keyword">except</span> jwt.InvalidTokenError:</span><br><span class="line">            <span class="keyword">raise</span> AuthenticationFailed(<span class="string">'非法用户'</span>)</span><br><span class="line">        username = jwt_get_username_from_payload(payload)</span><br><span class="line">        print(username)</span><br><span class="line">        user = User.objects.filter(username=username).first()</span><br><span class="line">        print(user)</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> user, jwt_value</span><br></pre></td></tr></table></figure>

<h3 id="4-4-登陆获取token"><a href="#4-4-登陆获取token" class="headerlink" title="4.4 登陆获取token"></a>4.4 登陆获取token</h3><p><img src="https://tva1.sinaimg.cn/large/007S8ZIlgy1ggjrfa03aaj312z0u0afg.jpg" alt="image-20200708185227693"></p>
<h3 id="4-5-编写测试接口"><a href="#4-5-编写测试接口" class="headerlink" title="4.5 编写测试接口"></a>4.5 编写测试接口</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> users.app_auth <span class="keyword">import</span> JSONWebTokenAuthentication,MyJSONWebTokenAuthentication</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">OrderView</span><span class="params">(APIView)</span>:</span></span><br><span class="line">    <span class="comment"># authentication_classes = [JSONWebTokenAuthentication]</span></span><br><span class="line">    authentication_classes = [MyJSONWebTokenAuthentication]</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">get</span><span class="params">(self,request)</span>:</span></span><br><span class="line">        print(request.user)</span><br><span class="line">        <span class="keyword">return</span> CommonResponse(<span class="string">'100'</span>, <span class="string">'成功'</span>,&#123;<span class="string">'数据'</span>:<span class="string">'测试'</span>&#125;)</span><br></pre></td></tr></table></figure>

<h3 id="4-6-测试"><a href="#4-6-测试" class="headerlink" title="4.6 测试"></a>4.6 测试</h3><p><img src="https://tva1.sinaimg.cn/large/007S8ZIlgy1ggjrg9ots0j31d60rcjv6.jpg" alt="image-20200708185327976"></p>
</section>
    <!-- Tags START -->
    
    <!-- Tags END -->
    <!-- NAV START -->
    
  <div class="nav-container">
    <!-- reverse left and right to put prev and next in a more logic postition -->
    
      <a class="nav-left" href="/python/Django-rest-framework%E6%A1%86%E6%9E%B6/6-drf-%E8%AE%A4%E8%AF%81%E6%9D%83%E9%99%90%E9%A2%91%E7%8E%87/">
        <span class="nav-arrow">← </span>
        
          python/Django-rest-framework框架/6-drf-认证权限频率
        
      </a>
    
    
      <a class="nav-right" href="/python/Django-rest-framework%E6%A1%86%E6%9E%B6/10-drf-Xadmin%E7%9A%84%E4%BD%BF%E7%94%A8/">
        
          python/Django-rest-framework框架/10-drf-Xadmin的使用
        
        <span class="nav-arrow"> →</span>
      </a>
    
  </div>

    <!-- NAV END -->
    <!-- 打赏 START -->
    
      <div class="money-like">
        <div class="reward-btn">
          赏
          <span class="money-code">
            <span class="alipay-code">
              <div class="code-image"></div>
              <b>使用支付宝打赏</b>
            </span>
            <span class="wechat-code">
              <div class="code-image"></div>
              <b>使用微信打赏</b>
            </span>
          </span>
        </div>
        <p class="notice">点击上方按钮,请我喝杯咖啡！</p>
      </div>
    
    <!-- 打赏 END -->
    <!-- 二维码 START -->
    
      <div class="qrcode">
        <canvas id="share-qrcode"></canvas>
        <p class="notice">扫描二维码，分享此文章</p>
      </div>
    
    <!-- 二维码 END -->
    
      <!-- Gitment START -->
      <div id="comments"></div>
      <!-- Gitment END -->
    
  </article>
  <!-- Article END -->
  <!-- Catalog START -->
  
    <aside class="catalog-container">
  <div class="toc-main">
  <!-- 不蒜子统计 -->
    <strong class="toc-title">目录</strong>
    
      <ol class="toc-nav"><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#一-JWT认证"><span class="toc-nav-text">一 JWT认证</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#1-1-构成和工作原理"><span class="toc-nav-text">1.1 构成和工作原理</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#JWT的构成"><span class="toc-nav-text">JWT的构成</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#1-1-1-header"><span class="toc-nav-text">1.1.1 header</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#1-1-2-payload"><span class="toc-nav-text">1.1.2 payload</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#1-1-3-signature"><span class="toc-nav-text">1.1.3 signature</span></a></li></ol></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#1-2-本质原理"><span class="toc-nav-text">1.2 本质原理</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#jwt认证算法：签发与校验"><span class="toc-nav-text">jwt认证算法：签发与校验</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-5"><a class="toc-nav-link" href="#签发：根据登录请求提交来的-账号-密码-设备信息-签发-token"><span class="toc-nav-text">签发：根据登录请求提交来的 账号 + 密码 + 设备信息 签发 token</span></a></li><li class="toc-nav-item toc-nav-level-5"><a class="toc-nav-link" href="#校验：根据客户端带token的请求-反解出-user-对象"><span class="toc-nav-text">校验：根据客户端带token的请求 反解出 user 对象</span></a></li></ol></li></ol></li></ol></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#drf项目的jwt认证开发流程（重点）"><span class="toc-nav-text">drf项目的jwt认证开发流程（重点）</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#1-2-1-补充base64编码解码"><span class="toc-nav-text">1.2.1 补充base64编码解码</span></a></li></ol></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#二-drf-jwt安装和简单使用"><span class="toc-nav-text">二 drf-jwt安装和简单使用</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-5"><a class="toc-nav-link" href="#2-1-官网"><span class="toc-nav-text">2.1 官网</span></a></li><li class="toc-nav-item toc-nav-level-5"><a class="toc-nav-link" href="#2-2-安装"><span class="toc-nav-text">2.2 安装</span></a></li><li class="toc-nav-item toc-nav-level-5"><a class="toc-nav-link" href="#2-3-使用："><span class="toc-nav-text">2.3 使用：</span></a></li></ol></li></ol></li></ol></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#三-实战之使用Django-auth的User表自动签发"><span class="toc-nav-text">三 实战之使用Django auth的User表自动签发</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#3-1-配置setting-py"><span class="toc-nav-text">3.1 配置setting.py</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#3-2-编写序列化类ser-py"><span class="toc-nav-text">3.2 编写序列化类ser.py</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-5"><a class="toc-nav-link" href="#3-3-自定义认证返回结果（setting中配置的）"><span class="toc-nav-text">3.3 自定义认证返回结果（setting中配置的）</span></a></li></ol></li></ol></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#3-4-基于drf-jwt的全局认证："><span class="toc-nav-text">3.4 基于drf-jwt的全局认证：</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#3-5-全局使用"><span class="toc-nav-text">3.5 全局使用</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#3-6-局部启用禁用"><span class="toc-nav-text">3.6 局部启用禁用</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#3-7-多方式登录："><span class="toc-nav-text">3.7 多方式登录：</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#3-8-配置多方式登录"><span class="toc-nav-text">3.8 配置多方式登录</span></a></li></ol></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#四-实战之自定义User表，手动签发"><span class="toc-nav-text">四 实战之自定义User表，手动签发</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#4-1-手动签发JWT："><span class="toc-nav-text">4.1 手动签发JWT：</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#4-2-编写登陆视图类"><span class="toc-nav-text">4.2 编写登陆视图类</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#4-3-编写认证组件"><span class="toc-nav-text">4.3 编写认证组件</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#4-4-登陆获取token"><span class="toc-nav-text">4.4 登陆获取token</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#4-5-编写测试接口"><span class="toc-nav-text">4.5 编写测试接口</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#4-6-测试"><span class="toc-nav-text">4.6 测试</span></a></li></ol></li></ol></li></ol>
    
  </div>
</aside>
  
  <!-- Catalog END -->
</main>

<script>
  (function () {
    var url = 'http://www.liuqingzheng.top/python/Django-rest-framework框架/9-drf-JWT认证/';
    var banner = ''
    if (banner !== '' && banner !== 'undefined' && banner !== 'null') {
      $('#article-banner').css({
        'background-image': 'url(' + banner + ')'
      })
    } else {
      $('#article-banner').geopattern(url)
    }
    $('.header').removeClass('fixed-header')

    // error image
    $(".markdown-content img").on('error', function() {
      $(this).attr('src', 'http://file.muyutech.com/error-img.png')
      $(this).css({
        'cursor': 'default'
      })
    })

    // zoom image
    $(".markdown-content img").on('click', function() {
      var src = $(this).attr('src')
      if (src !== 'http://file.muyutech.com/error-img.png') {
        var imageW = $(this).width()
        var imageH = $(this).height()

        var zoom = ($(window).width() * 0.95 / imageW).toFixed(2)
        zoom = zoom < 1 ? 1 : zoom
        zoom = zoom > 2 ? 2 : zoom
        var transY = (($(window).height() - imageH) / 2).toFixed(2)

        $('body').append('<div class="image-view-wrap"><div class="image-view-inner"><img src="'+ src +'" /></div></div>')
        $('.image-view-wrap').addClass('wrap-active')
        $('.image-view-wrap img').css({
          'width': `${imageW}`,
          'transform': `translate3d(0, ${transY}px, 0) scale3d(${zoom}, ${zoom}, 1)`
        })
        $('html').css('overflow', 'hidden')

        $('.image-view-wrap').on('click', function() {
          $(this).remove()
          $('html').attr('style', '')
        })
      }
    })
  })();
</script>


  <script>
    var qr = new QRious({
      element: document.getElementById('share-qrcode'),
      value: document.location.href
    });
  </script>



  <script>
    var gitmentConfig = "liuqingzheng";
    if (gitmentConfig !== 'undefined') {
      var gitment = new Gitment({
        id: "python/Django-rest-framework框架/9-drf-JWT认证",
        owner: "liuqingzheng",
        repo: "FuckBlog",
        oauth: {
          client_id: "32a4076431cf39d0ecea",
          client_secret: "94484bd79b3346a949acb2fda3c8a76ce16990c6"
        },
        theme: {
          render(state, instance) {
            const container = document.createElement('div')
            container.lang = "en-US"
            container.className = 'gitment-container gitment-root-container'
            container.appendChild(instance.renderHeader(state, instance))
            container.appendChild(instance.renderEditor(state, instance))
            container.appendChild(instance.renderComments(state, instance))
            container.appendChild(instance.renderFooter(state, instance))
            return container;
          }
        }
      })
      gitment.render(document.getElementById('comments'))
    }
  </script>




    <div class="scroll-top">
  <span class="arrow-icon"></span>
</div>
    <footer class="app-footer">
<!-- 不蒜子统计 -->
<span id="busuanzi_container_site_pv">
     本站总访问量<span id="busuanzi_value_site_pv"></span>次
</span>
<span class="post-meta-divider">|</span>
<span id="busuanzi_container_site_uv" style='display:none'>
     本站访客数<span id="busuanzi_value_site_uv"></span>人
</span>
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>



  <p class="copyright">
    &copy; 2021 | Proudly powered by <a href="https://www.cnblogs.com/xiaoyuanqujing" target="_blank">小猿取经</a>
    <br>
    Theme by <a href="https://www.cnblogs.com/xiaoyuanqujing" target="_blank" rel="noopener">小猿取经</a>
  </p>
</footer>

<script>
  function async(u, c) {
    var d = document, t = 'script',
      o = d.createElement(t),
      s = d.getElementsByTagName(t)[0];
    o.src = u;
    if (c) { o.addEventListener('load', function (e) { c(null, e); }, false); }
    s.parentNode.insertBefore(o, s);
  }
</script>
<script>
  async("//cdnjs.cloudflare.com/ajax/libs/fastclick/1.0.6/fastclick.min.js", function(){
    FastClick.attach(document.body);
  })
</script>

<script>
  var hasLine = 'true';
  async("//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/highlight.min.js", function(){
    $('figure pre').each(function(i, block) {
      var figure = $(this).parents('figure');
      if (hasLine === 'false') {
        figure.find('.gutter').hide();
      }
      var lang = figure.attr('class').split(' ')[1] || 'code';
      var codeHtml = $(this).html();
      var codeTag = document.createElement('code');
      codeTag.className = lang;
      codeTag.innerHTML = codeHtml;
      $(this).attr('class', '').empty().html(codeTag);
      figure.attr('data-lang', lang.toUpperCase());
      hljs.highlightBlock(block);
    });
  })
</script>





<!-- Baidu Tongji -->

<script>
    var _baId = 'c5fd96eee1193585be191f318c3fa725';
    // Originial
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?" + _baId;
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
</script>


<script src="/js/script.js"></script>


<script src="/js/search.js"></script>


<script src="/js/load.js"></script>



  <span class="local-search local-search-google local-search-plugin" style="right: 50px;top: 70px;;position:absolute;z-index:2;">
      <input type="search" placeholder="站内搜索" id="local-search-input" class="local-search-input-cls" style="">
      <div id="local-search-result" class="local-search-result-cls"></div>
  </span>


  </body>
</html>